from parser import parseXML
from handler import CodeHandler, headers

headers = dict(headers)

def getTwillShellCommands(filedata, initialGo=True, userAgent=True, debug=True):
    actions = parseXML(filedata)
    if not initialGo:
        FIRSTACTION = 0
        if actions[FIRSTACTION]['type'] == 'goto':
            dummy = actions.pop(FIRSTACTION)
    t = TwillShellHandler(actions, userAgent=userAgent,
        debug=debug)
    t.process()
    return t.getResults()

def getInitialURL(filedata):
    actions = parseXML(filedata)
    for a in actions:
        if a['type']=="goto":
            return a['value']

class TwillShellHandler(CodeHandler):

    def __init__(self, actions, userAgent=True, debug=True):
        self.isUserAgent = userAgent
        self.isDebug = debug
        super(TwillShellHandler, self).__init__(actions)
    
    def process(self):
        if self.isDebug:
            self.code("debug commands 1")
        if self.isUserAgent:
            self.code("agent '%s'" % (headers['User-Agent']))
        super(TwillShellHandler, self).process()

    def goto(self, action):
        self.code("go %s" % action['value'])

    def verifyTitle(self, action):
        self.code('title "%s"' % action['value'])

    def assertTextExists(self, action):
        regex = action["value"]
        self.code('find "%s"' % regex)

    def assertTextDoesNotExist(self, action):
        regex = action["value"]
        self.code('notfind "%s"' % regex)

    def fill(self, action):
        xpath = action['xpath']
        formName = self.getFormIdentity(xpath)
        fieldName = self.getFormElementName(xpath)
        fieldValue = action['value']
        self.code('formvalue %s %s "%s"' % (formName, fieldName, fieldValue))

    def click(self, action):
        xpath = action['xpath']
        if xpath.startswith("*/FORM"):
            # first "click" button
            formName = self.getFormIdentity(xpath)
            fieldName = self.getFormElementName(xpath)
            fieldValue = self.getFormElementValue(xpath)
            self.code('formvalue %s %s "%s"' % (formName, fieldName, fieldValue))
            # then submit
            self.code("submit")
        elif '/A[' in xpath:
            linkName = self.getLinkName(xpath)
            self.code('follow "%s"' % linkName)

    def check(self, action):
        self.click(action)

    def select(self, action):
        self.fill(action)
        
if __name__ == "__main__":
    import sys
    filename = sys.argv[1]
    print getTwillShellCommands(filename)
